package com.lixingye.meowstar.interceptor;

import com.lixingye.meowstar.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 猫大仙
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${meowstar-forum.login.url}")
    private String defaultURL;
    /**
     * 登录拦截器
     * @param request
     * @param response
     * @param handler
     * @return  true:继续 <br/>false:拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session!=null && session.getAttribute(AppConfig.USER_SESSION)!=null){
            //用户已登录
            return true;
        }
        //判断URL是否正确
        if(!defaultURL.startsWith("/")){
            defaultURL = "/"+defaultURL;
        }
        //校验未通过
        //跳转到登录页面
        response.sendRedirect(defaultURL);
        //中断流程
        return false;
    }
}
